/*
 * @Author: lineCode 1145938682@qq.com
 * @Date: 2024-12-19 16:11:49
 * @LastEditors: lineCode 1145938682@qq.com
 * @LastEditTime: 2025-08-28 23:37:46
 * @FilePath: /backend/shorthand-modules/shorthand-modules-content/src/main/java/com/angus/modules/content/service/impl/SysOrderServiceImpl.java
 */
package com.angus.modules.content.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.angus.api.front.domain.FrontUser;
import com.angus.common.core.utils.uuid.IdUtils;
import com.angus.common.security.utils.SecurityUtils;
import com.angus.modules.content.domain.Course;
import com.angus.modules.content.domain.SysOrder;
import com.angus.modules.content.dto.CreateOrderDto;
import com.angus.modules.content.dto.QueryOrderDto;
import com.angus.modules.content.mapper.FrontUserMapper;
import com.angus.modules.content.repository.CourseRepository;
import com.angus.modules.content.repository.SysOrderRepository;
import com.angus.modules.content.service.SysOrderService;
import com.angus.modules.content.vo.CommonVo;
import com.angus.modules.content.vo.SysOrderVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;


/**
 * @author lineCode
 */
@Service
public class SysOrderServiceImpl implements SysOrderService {

    @Resource
    private SysOrderRepository sysOrderRepository;

    @Resource
    private CourseRepository courseRepository;

    @Resource
    private FrontUserMapper frontUserMapper;

    @Override
    public CommonVo<SysOrderVo> getOrderList(QueryOrderDto dto, Long userId) {

        String startTime = dto.getStartTime();
        String endTime = dto.getEndTime();
        if (CharSequenceUtil.isNotBlank(dto.getStartTime()) && CharSequenceUtil.isNotBlank(dto.getEndTime())) {
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
        }
        // 如果是后端服务请求，则 userId 为空，不查询 user_id
        if (dto.getIsAdmin() != null && dto.getIsAdmin() == 1){
            userId = 0L;
        }
        List<SysOrder> orderList = sysOrderRepository.getOrderList(dto.getOrderNo(),
                dto.getCourseCode(), dto.getCourseName(), userId, dto.getPayMethod(),
                dto.getStatus(), dto.getRecommendCode(),
                startTime, endTime, dto.getPageNum(), dto.getPageSize());

        CommonVo<SysOrderVo> vo = new CommonVo<>();
        if (!orderList.isEmpty()) {
            List<SysOrderVo> data = SysOrderVo.mapToVo(orderList);
            data.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
            vo.setData(data);
            vo.setTotalCount(sysOrderRepository.countOrder(
                    dto.getOrderNo(),
                    dto.getCourseCode(),
                    dto.getStatus(),
                    dto.getPayMethod(),
                    startTime,
                    endTime,
                    true
            ));
        }
        return vo;
    }

    @Override
    public List<SysOrderVo> getPendingOrderList(String courseCode, Long userId) {

        List<SysOrderVo> orderVoList = new ArrayList<>();
        List<SysOrder> orderList = sysOrderRepository.getPendingOrderList(courseCode,userId);

        for (SysOrder order : orderList) {
            SysOrderVo orderVo = new SysOrderVo();
            orderVo.setOrderNo(order.getOrderNo());
            orderVo.setUserId(order.getUserId());
            orderVo.setCourseCode(order.getCourseCode());
            orderVo.setCourseName(order.getCourseName());
            orderVo.setCourseType(order.getCourseType());
            orderVo.setCourseAmount(order.getCourseAmount());
            orderVo.setStatus(order.getStatus());
            orderVo.setPayMethod(order.getPayMethod());
            orderVo.setRecommendCode(order.getRecommendCode());
            orderVo.setPayTime(order.getPayTime());
            orderVo.setExpireTime(order.getExpireTime());
            orderVo.setCreateTime(order.getCreateTime());
            orderVoList.add(orderVo);
        }
        return orderVoList;
    }

    @Override
    public SysOrderVo createOrder(CreateOrderDto dto, Long userId) {
        // 获取课程信息
        Course course = courseRepository.getCourseByCode(dto.getCourseCode());
        //
        FrontUser frontUser = frontUserMapper.selectById(userId);
        if (frontUser == null || frontUser.getUserId() == 0) {
            throw new IllegalArgumentException("用户不存在");
        }
        // 生成订单
        SysOrder order = new SysOrder();
        order.setOrderNo(IdUtils.generateOrderId());
        order.setCourseAmount(dto.getCourseAmount());
        order.setCourseCode(dto.getCourseCode());
        order.setCourseName(course.getCourseName());
        order.setCourseType(course.getContentType());
        order.setValidDays(course.getValidDays() == null ? 365 : course.getValidDays());
        order.setPayMethod(dto.getPayMethod());
        order.setUserId(userId);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setUpdateBy(SecurityUtils.getUsername());
        //待支付
        order.setStatus(1);
        // 如果不是自己的推荐码，则填写
        if (dto.getRecommendCode() != null) {
            if (frontUser.getRecommendCode() != null && !frontUser.getRecommendCode().equals(dto.getRecommendCode())) {
                // 查询推荐人信息
                FrontUser recommendUser = frontUserMapper.selectOne(Wrappers.lambdaQuery(FrontUser.class)
                        .eq(FrontUser::getRecommendCode, dto.getRecommendCode())
                        .eq(FrontUser::getDelFlag, 0));
                if (recommendUser != null && recommendUser.getUserId() != 0) {
                    order.setRecommendCode(dto.getRecommendCode());
                }
            }
        }
        order.setCommissionRate(course.getCommissionRate());
        sysOrderRepository.save(order);
        // 返回支付信息
        SysOrderVo orderVo = new SysOrderVo();
        orderVo.setOrderNo(order.getOrderNo());
        orderVo.setUserId(order.getUserId());
        orderVo.setCourseCode(order.getCourseCode());
        orderVo.setCourseName(order.getCourseName());
        orderVo.setCourseAmount(order.getCourseAmount());
        orderVo.setCourseType(order.getCourseType());
        orderVo.setPayMethod(order.getPayMethod());
        orderVo.setStatus(order.getStatus());
        orderVo.setCreateTime(order.getCreateTime());
        return orderVo;
    }

    /**
     * 删除订单
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteByIds(List<Long> ids) {
        return sysOrderRepository.deleteByIds(ids);
    }
}
